from django.shortcuts import render

# Create your views here.
from .models import *
from myapp.serializers import UserSerializer, CateSerializer
from rest_framework.response import Response
from rest_framework.views import APIView


class RegView(APIView):
    def post(self, request):
        user_ser = UserSerializer(data=request.data)
        if user_ser.is_valid():
            user_ser.save()
            return Response({
                'code': 200,
                'data': '账户创建成功'
            })
        else:
            print(user_ser.errors)
            return Response({
                'code': 500,
                'data': '账户创建失败'
            })


class LogView(APIView):
    def post(self, request):
        data = request.data
        print(data)
        user_ser = User.objects.filter(username=data['username'], password=data['password']).first()
        if user_ser:
            return Response({
                'code': 200,
                'data': '登陆成功'
            })
        else:
            return Response({
                'code': 500,
                'data': '登陆失败,账号不存在'
            })


class CateView(APIView):
    def get(self, request):
        uid = request.GET.get('id', 0)
        if uid == 0:
            cate_list = Cate.objects.all()
            cate_ser = CateSerializer(instance=cate_list, many=True)
        else:
            cate = Cate.objects.filter(pk=uid).first()
            cate_ser = CateSerializer(instance=cate)
        return Response({
            'code': 200,
            'data': cate_ser.data
        })

    def post(self, request):
        uid = request.data.get('id')
        # print(uid)
        if not uid:
            cate_ser = CateSerializer(data=request.data)
            if cate_ser.is_valid():
                cate_ser.save()
                return Response({
                    'code': 200,
                    'data': '分类添加成功'
                })
            else:
                print(cate_ser.errors)
                return Response({
                    'code': 500,
                    'data': '分类添加失败'
                })
        else:
            name = request.data.get('newname')
            Cate.objects.filter(pk=uid).update(name=name)
            return Response({
                'code' : 200,
                'data' : '修改成功'
            })
    def delete(self, request):
        id = request.data.get('cid')
        Cate.objects.filter(pk=id).delete()
        return Response({
            'code' : 200,
            'data' : '删除成功'
        })

